package com.gitee.feizns.explore.data_structure.tree.bs.easy;

/**
 * 653. 两数之和 IV - 输入 BST
 * @author feizns
 * @since 2020/1/4
 */
public class FindTarget {

    public static void main(String[] args) {
        System.out.println(findTarget(create(), 4));
    }

    private static TreeNode create() {
        TreeNode ret = new TreeNode(2);
        ret.left = new TreeNode(1);
        ret.right = new TreeNode(3);
        return ret;
    }

    public static boolean findTarget(TreeNode root, int k) {
        return findTarget(root, root, k);
    }

    private static boolean findTarget(TreeNode root, TreeNode curt, int k) {
        if ( curt != null ) {
            int p = k - curt.val;
            if ( p != curt.val && exists(root, p) )
                return true;
            return findTarget(root, curt.left, k) || findTarget(root, curt.right, k);
        }
        return false;
    }

    private static boolean exists(TreeNode root, int k) {
        if ( root != null ) {
            if ( k < root.val )
                return exists(root.left, k);
            else if ( k > root.val )
                return exists(root.right, k);
            return true;
        }
        return false;
    }

}
